<template>
  <div class="forum-container">
    <div class="forum-header">
      <div class="forum-title">讨论区</div>
      <div class="comment-count">56</div>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-editor">
      <div class="editor-content">
        <textarea v-model="commentContent" placeholder="请输入评论..." @keydown.enter="handleSubmit"></textarea>
        <div class="send-btn" @click="handleSubmit">发送</div>
      </div>
    </div>

    <!-- 使用MdPreview显示评论内容 -->
    <div class="markdown-preview">
      <MdPreview :modelValue="markdownContent" @onHtmlChanged="handleHtmlClick" />
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, nextTick } from 'vue';
  import { MdPreview } from 'md-editor-v3';
  import 'md-editor-v3/lib/style.css';
  import commentsData from './commentsData.js'

  // 模拟数据
  const comments = ref([
    {
      id: '1',
      author: '张三',
      avatar: 'https://randomuser.me/api/portraits/men/22.jpg',
      content: '目前4G业务已经高速发展，5G在全国范围内的应用也在不断扩大，保障基站运行状态的稳定越来越重要。当前网络运维工作面临维护管理难度大、主动运维手段缺乏、智能化水平不足、降本增效压力大等诸多痛点，亟需提升运维精细管控能力和智能化水平。',
      createdAt: '6小时前',
      likes: 999,
      hasLiked: false,
      replies: []
    },
    {
      id: '2',
      author: '李四',
      avatar: 'https://randomuser.me/api/portraits/women/33.jpg',
      content: '目前4G业务已经高速发展，5G在全国范围内的应用也在不断扩大，保障基站运行状态的稳定越来越重要。当前网络运维工作面临维护管理难度大',
      createdAt: '5小时前',
      likes: 999,
      hasLiked: false,
      replies: [
        {
          id: '2-1',
          author: '王五',
          avatar: 'https://randomuser.me/api/portraits/men/44.jpg',
          content: `
# 前端资源汇总

这是一个包含**文字**、![图片](https://picsum.photos/600/300)和[链接](https://example.com)的完整示例。

点击下方链接访问常用资源：
- [Vue.js 官方文档](https://cn.vuejs.org/)
- [Tailwind CSS](https://tailwindcss.com/)

![前端开发](https://picsum.photos/seed/frontend/600/200)

> 提示：图片使用了占位符服务，实际使用时请替换为真实图片链接
`,
          createdAt: '4小时前',
          likes: 999,
          hasLiked: false,
          replyTo: '李四'
        }
      ]
    },
  ]);

  const commentContent = ref('');
  const toolbars = ['Link', 'Image', 'Quote'];

  // 生成Markdown内容
  const markdownContent = computed(() => {
    return comments.value.map(comment => {
      let md = `<div class="comment-item">
  <div class="avatar-container">
    
  </div>
  <div class="comment-content">
    <div class="comment-header">
      <div class="username">${comment.author}</div>
      <div class="time">${comment.createdAt}</div>
      <div class="like-count">${comment.likes}</div>
    </div>
    <div class="comment-text">${comment.content}</div>
    <div class="comment-actions">
      <div class="like-btn" data-id="${comment.id}" data-type="comment">
        ${comment.hasLiked ? '❤️' : '🤍'}
      </div>
      <div class="reply-btn" data-id="${comment.id}" data-author="${comment.author}">
        回复
      </div>
    </div>
  </div>
</div>`;

      if (comment.replies?.length) {
        md += `<div class="replies-list">`;
        comment.replies.forEach(reply => {
          md += `<div class="reply-item">
  <div class="avatar-container">
    
  </div>
  <div class="reply-content">
    <div class="reply-header">
      <div class="username">${reply.author}</div>
      <div class="reply-to">回复1 @${reply.replyTo}</div>
      <div class="time">${reply.createdAt}</div>
      <div class="like-count">${reply.likes}</div>
    </div>
    <p></p>
    <div class="reply-text">${reply.content}</div>
    <div class="reply-actions">
      <div class="like-btn" data-id="${reply.id}" data-type="reply">
        ${reply.hasLiked ? '❤️' : '🤍'}
      </div>
      <div class="reply-btn" data-parent="${comment.id}" data-author="${reply.author}">
        回复
      </div>
    </div>
  </div>
</div>`;
        });
        md += `</div>`;
      }

      return md;
    }).join('\n\n');
  });

  // 处理HTML交互
  const handleHtmlClick = () => {
    nextTick(() => {
      const container = document.querySelector('.markdown-preview');

      // 点赞处理
      container.querySelectorAll('.like-btn').forEach(btn => {
        btn.onclick = (e) => {
          const id = e.currentTarget.dataset.id;
          const type = e.currentTarget.dataset.type;

          if (type === 'comment') {
            const comment = comments.value.find(c => c.id === id);
            if (comment) {
              comment.hasLiked = !comment.hasLiked;
              comment.likes += comment.hasLiked ? 1 : -1;
            }
          } else {
            for (const comment of comments.value) {
              const reply = comment.replies?.find(r => r.id === id);
              if (reply) {
                reply.hasLiked = !reply.hasLiked;
                reply.likes += reply.hasLiked ? 1 : -1;
                break;
              }
            }
          }
        };
      });

      // 回复处理
      container.querySelectorAll('.reply-btn').forEach(btn => {
        btn.onclick = (e) => {
          const parentId = btn.dataset.parent || btn.dataset.id;
          const target = btn.dataset.author;
          commentContent.value = `回复 @${target}: `;
          document.querySelector('textarea').focus();
        };
      });
    });
  };

  // 其他方法
  const formatText = (format) => {
    const textarea = document.querySelector('textarea');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = commentContent.value.substring(start, end);

    let formattedText = '';
    switch (format) {
      case 'B': formattedText = `**${selectedText}**`; break;
      case 'I': formattedText = `*${selectedText}*`; break;
      case 'U': formattedText = `<u>${selectedText}</u>`; break;
      case 'Link': formattedText = `[${selectedText}](url)`; break;
      case 'Image': formattedText = ``; break;
      case 'Quote': formattedText = `> ${selectedText}`; break;
      default: formattedText = selectedText;
    }

    commentContent.value =
      commentContent.value.substring(0, start) +
      formattedText +
      commentContent.value.substring(end);
  };

  const handleSubmit = () => {
    if (!commentContent.value.trim()) return;

    comments.value.unshift({
      id: Date.now().toString(),
      author: '当前用户',
      avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
      content: commentContent.value,
      createdAt: '刚刚',
      likes: 0,
      hasLiked: false,
      replies: []
    });

    commentContent.value = '';
  };
</script>

<style scoped>
  .forum-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f0f7ff;
    border-radius: 8px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }

  .forum-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }

  .forum-title {
    color: #333;
    font-size: 22px;
    font-weight: 600;
  }

  .comment-count {
    color: #666;
    font-size: 16px;
    margin-left: 8px;
  }

  /* 评论输入框样式 */
  .comment-editor {
    margin-bottom: 20px;
    background: white;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .editor-content {
    display: flex;
    flex-direction: column;
  }

  textarea {
    width: 100%;
    min-height: 80px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    resize: vertical;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 10px;
  }

  .send-btn {
    align-self: flex-end;
    padding: 6px 16px;
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.2s;
    font-weight: 500;
    width: fit-content;
  }

  .send-btn:hover {
    background-color: #40a9ff;
  }

  /* Markdown预览容器 */
  .markdown-preview {
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }
</style>

<style>
  /* 全局样式用于Markdown渲染的内容 */
  .markdown-preview .comment-item {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  .markdown-preview .avatar-container {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
  }

  .markdown-preview .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
  }

  .markdown-preview .comment-content {
    flex: 1;
  }

  .markdown-preview .comment-header,
  .markdown-preview .reply-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    flex-wrap: wrap;
  }

  .markdown-preview .username {
    font-weight: 600;
    color: #333;
    margin-right: 8px;
    font-size: 15px;
  }

  .markdown-preview .time {
    color: #999;
    font-size: 12px;
    margin-right: 8px;
  }

  .markdown-preview .like-count {
    margin-left: auto;
    color: #666;
    font-size: 14px;
  }

  .markdown-preview .comment-text,
  .markdown-preview .reply-text {
    margin-bottom: 10px;
    line-height: 1.6;
    color: #333;
    font-size: 14px;
  }

  .markdown-preview .comment-actions,
  .markdown-preview .reply-actions {
    display: flex;
    gap: 15px;
  }

  .markdown-preview .like-btn,
  .markdown-preview .reply-btn {
    background: none;
    border: none;
    color: #666;
    cursor: pointer;
    padding: 4px 8px;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .markdown-preview .like-btn:hover,
  .markdown-preview .reply-btn:hover {
    background: #f5f5f5;
    border-radius: 4px;
  }

  .markdown-preview .reply-to {
    color: #1890ff;
    margin-right: 8px;
    font-size: 12px;
  }

  .markdown-preview .replies-list {
    margin-top: 15px;
    padding-left: 52px;
    border-left: 2px solid #eee;
  }

  .markdown-preview .reply-item {
    display: flex;
    gap: 12px;
    margin-bottom: 15px;
  }
</style>